package commons;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mysql.cj.protocol.Resultset;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class druidJdbcUtil {
    private  static DataSource dataSource;
    static {
        Connection conn=null;
        try {
            InputStream is = druidJdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            Properties prop=new Properties();
            prop.load(is);
            dataSource=DruidDataSourceFactory.createDataSource(prop);
        }catch (IOException e){
            throw  new ExceptionInInitializerError("加载数据库配置文件失败:"+e.getMessage());
        }
        catch (Exception e){
            throw  new ExceptionInInitializerError("初始化druid连接池失败"+e.getMessage());
        }
    }

    public static Connection getConnection()  {

        if(dataSource == null){
            throw new IllegalStateException("druid连接池未初始化,请检查配置文件和依赖");
        }
        try {
           return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败: " + e.getMessage(), e);
        }
    }

    public static void closeConnection(Connection conn){
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void closePrepareStatement(PreparedStatement ps){
        if(ps !=null){
            try {
                ps.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void closeResultSet(ResultSet rs){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void closeResource(Connection conn,PreparedStatement ps){
        closePrepareStatement(ps);
        closeConnection(conn);
    }
    public static void closeResource(Connection conn, PreparedStatement ps, ResultSet rs){
        closeResultSet(rs);
        closePrepareStatement(ps);
        closeConnection(conn);
    }
    public static void roolback(Connection conn){
        try {
            conn.rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
